/**
 * WidgetEventForm module
 */

 import eventHelper from "../../../utils/EventHelper";

 import React,{Component} from "react";
 import { connect } from 'dva';
 import classnames from 'classnames';
 import { bindActionCreators } from 'redux';
 import widgetsActions from '../../../actions/Editor/widgets';
 import editorActions from '../../../actions/Editor/editor';
 import tool from "../../../utils/tool";
 import consts from "../../../consts/consts";
 import Validator from "../../../utils/validator/Validator";

 class WidgetEventForm extends Component {
    constructor(props) {
        super(props);
        this.state = {             
            showForm: false,
            title: '',
            widget: {}
        };
    }
    getInitialProps(){
        return {
            root: {},
            form: {},
            widget: {}
        }
    }
    componentWillMount(){
        const {widget} = this.props, {action} = widget || {},{form_type} = action.form_type || 0;
        this.title = action.title || consts.FORMTYPE[form_type].value;

        this.note = action.form_items['message'] ? action.form_items['message'].note: '';

        let param = {};

        if(this.title){
            param['title'] = this.title;
        }
        if(this.note){
            param['note'] = this.note;
        }
        param['widget']= widget;
        this.setState(param);
    }
    componentDidMount(){
        this.initElements();
    }
    componentWillUnmount(){
        this.updateEvent();
    }
    initElements(){
        this.elements = {
        };
    }
    handleOnUpdateEvent(){
        this.updateWidget(widget);
    }
    handleOnChangeFormType(e){
        const {widget} = this.props;
        let element = $(e.target), val = parseInt(element.val());
        let data = widget;
        data.action = $.extend(true, {}, widget.action, {form_type: val});

        data.tip_text = consts.FORMTYPE[val].value;//重置tip_text
        
        tool.reBuildFormContent(widget);//重置对应表单内容
        data.action.title = consts.FORMTYPE[val].value;//重置title

        if(val == 3){
            data.action.reorder = [];
        }
        this.title = data.action.title;
        this.setState({
            title: this.title,
            note: ''
        });

        this.updateWidget(data);
    }
    toggleFormLists(){
        const showForm = this.state.showForm;
        this.setState({
            showForm: !showForm
        })
    }
    handleOnChangeTitle(e){//标题
        const input = this.focusItem = $(e.target || e.srcElement);
        const name = input.attr('name');
        if(name == 'title'){//标题
            this.title = input.val().replace(/<.*?>/ig,"");
            if(this.title.length > 12){
                this.title = this.title.slice(0,12);
            }
            this.setState({
                title: this.title
            });
        } else if(name == 'note'){//留言
            this.note = input.val().replace(/<.*?>/ig,"");
            if(this.note.length > 72){
                this.note = this.note.slice(0,72);
            }
            this.setState({
                note: this.note
            });
        }

    }
    updateEvent(){
        const {widget} = this.props, {action} = widget || {};
        const input = this.focusItem;
        if(!input) return false;
        const type = input.attr("name");
        if(type == 'title'){
            if(this.title.length > 12){
                this.title = this.title.slice(0,12);
            }
            var newData = this.rebuildActionData('title',this.title);
            widget.action = $.extend(action,newData);

        } else if(type == 'note'){
            if(this.note.length > 72){
                this.note = this.note.slice(0,72);
            }
            widget.action.form_items['message'].note = this.note;
        }

        this.updateWidget(widget);
    }
    handleOnChangeRequired(e){
        const {widget} = this.props;
        let className = "icon-form-item",
            element = $(e.target || e.srcElement);
        element = element.hasClass(className) ? element : element.parents("." + className);

        let name = element.attr("data-name");
        let val = parseInt(element.attr('data-value'));
        let form_items = widget.action.form_items;

        let newData = this.rebuildActionData('required', Number(!val));
        let obj = form_items[name] || {};
        let param = null;

        if(name == "SMS"){//短信验证处理
            form_items['phone'].SMS.required = Number(!val);
            this.updateWidget(widget);
            return;
        }
        $.extend(obj,param);
        form_items[name] = $.extend(obj,newData);
        this.updateWidget(widget);
    }
    handleOnAddForm(){
        let showForm = this.state.showForm;
        this.setState({
            showForm: true
        })
    }
    handleOnAddCustomForm(e){
        const {widget} = this.props;
        let form_items = widget.action.form_items || {},
            custom_form = consts.ALLFORMCONTENTITEM;
        var className = "form_container_item";
        var element = $(e.target || e.srcElement);
        element = element.hasClass(className) ? element : element.parents("." + className);
        var name = element.attr('data-name'),
            checked = parseInt(element.attr('data-value'));
        var reorder = widget.action.reorder || [];

        if(Number(!checked)){
            form_items[name] = this.reBuildCustomFormData(name);
            reorder.push(name);
        } else {
            var index = reorder.indexOf(name);
            reorder.splice(index,1);
            delete form_items[name];
        }
        this.updateWidget(widget);
    }
    reBuildCustomFormData(param){
        var defaultValue = {//name对应value值
            name: $._("Full name"),
            sex: $._("Sex"),
            phone: $._("Guest phone"),
            email: $._("Email"),
            company:$._("Company"),
            address:$._("Address"),
            message:$._("Message")
        }
        var newData = {
            required: 0,
            name: param,
            value: defaultValue[param]
        };
        if(param ==　"phone"){
            var param = {
                name:'SMS',
                required: 0,
                value: $._("need sms verify")
            }
            newData["SMS"] = param;
        }
        return newData;
    }
    rebuildActionData(type, val){
        var newData = {};
        newData[type] = val;
        return newData;
    }
    reBuildArray(array){
        var widget = this.props.widget,
            form_type = widget.action.form_type,
            reorder = widget.action.reorder || [];

        var newFormItems = [];
        for (var i in reorder){
            var item = array[reorder[i]];
            newFormItems.push(item);
        }
        return newFormItems;
    }
    reBuildCustomForm(){
        var widget = this.props.widget;
        var custom_form = consts.ALLFORMCONTENTITEM;
        var form_items = widget.action.form_items || {};
        for(var i in custom_form){
            custom_form[i].checked = 0;
            if(form_items[custom_form[i].name]){
                custom_form[i].checked = 1;
            }
        }

        var form = $.extend(custom_form,form_items);

        return form;
    }
    updateWidget(widget){
        const {updateWidget,setState,fromTemplate} = this.props;
        if(fromTemplate){
//            root.updateLocaleWidget(widget);
//            this.setState({
//                widget: widget
//            })
            alert('can not close dialog');
        } else {
            setState({selectedWidget: widget});
            updateWidget(widget);
            eventHelper.trigger(consts.EVENTS.THREED_WIDGET_PROPERTY_CHANGED, widget);
        }
    }
    render(){
        const {fromTemplate,widget: data} = this.props;
        let widget = fromTemplate ? this.state.widget: data,
            action = widget.action;
        let formTypes = consts.FORMTYPE;
        let oldForm_Items = action.form_items || {};
        let form_Items = this.reBuildArray(oldForm_Items);
        let showForm = this.state.showForm;
        let if_custom = action.form_type == consts.FORM_TYPES.CUSTOM;
        let title = this.state.title;
        let note = this.state.note;

        let customFormNode = "";
        let addFormNode = "";
        if(if_custom){//自定义表单
            let self = this;
            customFormNode =
                <div className='form_content'>
                    <div>{$._('Please add or reset form contents')}</div>
                    <div className='form_container' style={{display: showForm ? 'block': 'none'}}>
                        <div className='form_container_title'>{$._('Choose add form contents')}</div>
                        <div className='form_container_content'>
                            {
                                self.reBuildCustomForm().map(function(item,index){
                                    return(
                                        <div className='form_container_item' key={index} onClick={(e) => self.handleOnAddCustomForm(e)} data-name={item.name} data-value={item.checked}>
                                            <span className={"icon-form-item " + (item.checked ? "icon-uniF52F" : "icon-uniF471")} ></span>
                                            <span className=''>{item.value}</span>
                                        </div>
                                    )
                                })
                            }
                        </div>
                        <div className="trigger-btn" onClick={() => this.toggleFormLists()}>{$._("Confirm")}</div>
                    </div>
                </div>
                addFormNode =
                    <span className='icon_add_form' onClick={() => this.handleOnAddForm()}></span>
        }
        return (
            <div className="form_event">
                <div className='form_select'>
                    <label>{$._("Form type")}</label>
                    <select value={action.form_type} onChange={(e) => this.handleOnChangeFormType(e)} className='form-control'>
                        {
                            formTypes.map(function(formType,index){
                                return(
                                    <option value={formType.type} key={index} >{formType.value}</option>
                                )
                             })
                         }
                    </select>
                </div>
                <div className='form_title'>
                    <span>{$._("Title")}</span>
                    <input type='text' max='' value={title} onChange={(e) => this.handleOnChangeTitle(e)} name='title' onBlur={() => this.updateEvent()} className='form-control'/>
                </div>
                <div className='form_contents'>
                    <div className='form_title'>
                        <span>{$._("Form contents")}</span>
                        {addFormNode}
                    </div>
                    {customFormNode}
                    <div className='form_content'>
                        {
                            form_Items.map(function(group,index){
                                var needVerifyNode = "";
                                var need_message = group['SMS'];
                                if(group.name == 'phone' && need_message){
                                   needVerifyNode =
                                       <div className='need_verify'>
                                           <span className='item-name'>{need_message.value}</span>
                                            <span className='item-checkbox'>
                                                <span className={"icon-form-item " + (need_message.required ? "icon-uniF52F" : "icon-uniF471")} onClick={(e) => this.handleOnChangeRequired(e)} data-name={need_message.name} data-value={need_message.required}></span>
                                                <span style={{visibility:'hidden'}}>{$._("Required")}</span>
                                            </span>
                                            <div className='form_link'>{$._("Account remaining 1000 free SMS verification")}</div>
                                        </div>
                                }

                                var MessageNode = "";
                                if(group.name == 'message'){
                                    MessageNode =
                                        <div className='message'>
                                            <textarea name="note" onChange={(e) => this.handleOnChangeTitle(e)} onBlur={() => this.updateEvent()} type="text" className=".form-control text-input" value={note}></textarea>
                                        </div>
                                }
                                return(
                                    <div className='content-items' key={index}>
                                        <span className='item-name'>{group.value}</span>
                                        <span className='item-checkbox'>
                                            <span className={"icon-form-item " + (group.required ? "icon-uniF52F" : "icon-uniF471")} name='required' onClick={(e) => this.handleOnChangeRequired(e)} data-name={group.name} data-value={group.required}></span>
                                            <span>{$._("Required")}</span>
                                        </span>
                                        {needVerifyNode}
                                        {MessageNode}
                                    </div>
                                )
                            }.bind(this))
                        }
                    </div>

                </div>
            </div>
        )
    }
 }

 const mapStateToProps = ({ editor, widgets ,pages}) => {
  const pageId = editor.selectedPageId;
  return {
      status: editor.status,
      fromTemplate: editor.fromTemplate,
      widget: editor.selectedWidget,
      widgets: widgets.filter(w => w.page_id === pageId),
      pages,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEventForm);
